#!/bin/bash

# ArXiv Subscription Platform - Native Build Script
# Builds and deploys the platform without Docker

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Configuration
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BUILD_DIR="${PROJECT_ROOT}/build"
BACKEND_DIR="${PROJECT_ROOT}/backend"
FRONTEND_DIR="${PROJECT_ROOT}/frontend" 
DATABASE_DIR="${PROJECT_ROOT}/database"
VENV_DIR="${PROJECT_ROOT}/venv"
LOG_DIR="${PROJECT_ROOT}/logs"

# Default configuration
ENVIRONMENT=${ENVIRONMENT:-production}
PORT=${PORT:-8000}
FRONTEND_PORT=${FRONTEND_PORT:-3000}
DATABASE_URL=${DATABASE_URL:-postgresql://arxiv_user:arxiv_pass@localhost:5432/arxiv_platform}
REDIS_URL=${REDIS_URL:-redis://localhost:6379}

print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

check_dependencies() {
    print_status "Checking system dependencies..."
    
    # Check Python 3.8+
    if ! command -v python3 &> /dev/null; then
        print_error "Python 3 is required but not installed"
        exit 1
    fi
    
    python_version=$(python3 -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')
    required_version="3.8"
    if python3 -c "import sys; exit(0 if sys.version_info >= (3, 8) else 1)"; then
        print_success "Python version $python_version is compatible (3.8+ required)"
    else
        print_error "Python 3.8+ is required, found $python_version"
        exit 1
    fi
    
    # Check Node.js for frontend
    if ! command -v node &> /dev/null; then
        print_warning "Node.js not found, frontend will not be built"
        SKIP_FRONTEND=true
    fi
    
    # Check PostgreSQL
    if ! command -v psql &> /dev/null; then
        print_warning "PostgreSQL client not found, database setup may fail"
    fi
    
    # Check Redis
    if ! command -v redis-cli &> /dev/null; then
        print_warning "Redis client not found, caching may not work"
    fi
    
    print_success "Dependency check completed"
}

setup_python_environment() {
    print_status "Setting up Python virtual environment..."
    
    # Create virtual environment
    if [ ! -d "$VENV_DIR" ]; then
        python3 -m venv "$VENV_DIR"
    fi
    
    # Activate virtual environment
    source "$VENV_DIR/bin/activate"
    
    # Upgrade pip
    pip install --upgrade pip
    
    # Install backend dependencies
    if [ -f "$BACKEND_DIR/requirements.txt" ]; then
        pip install -r "$BACKEND_DIR/requirements.txt"
    fi
    
    # Install email service dependencies
    if [ -f "$BACKEND_DIR/requirements.email.txt" ]; then
        pip install -r "$BACKEND_DIR/requirements.email.txt"
    fi
    
    # Install additional production dependencies
    pip install gunicorn supervisor psycopg2-binary redis celery
    
    print_success "Python environment setup completed"
}

setup_database() {
    print_status "Setting up PostgreSQL database..."
    
    # Check if database exists
    DB_EXISTS=$(psql -lqt | cut -d \| -f 1 | grep -qw arxiv_platform && echo "yes" || echo "no")
    
    if [ "$DB_EXISTS" = "no" ]; then
        print_status "Creating database..."
        createdb arxiv_platform || print_warning "Database creation failed, assuming it exists"
    fi
    
    # Run migrations
    if [ -f "$DATABASE_DIR/database_schema.sql" ]; then
        print_status "Running database migrations..."
        psql "$DATABASE_URL" -f "$DATABASE_DIR/database_schema.sql"
    fi
    
    # Load seed data
    if [ -f "$DATABASE_DIR/seed_data.sql" ]; then
        print_status "Loading seed data..."
        psql "$DATABASE_URL" -f "$DATABASE_DIR/seed_data.sql"
    fi
    
    print_success "Database setup completed"
}

build_frontend() {
    if [ "$SKIP_FRONTEND" = true ]; then
        print_warning "Skipping frontend build (Node.js not available)"
        return
    fi
    
    print_status "Building frontend..."
    
    cd "$FRONTEND_DIR"
    
    # Install dependencies
    if [ -f "package.json" ]; then
        npm install
        
        # Build for production
        npm run build
        
        # Create static file serving directory
        mkdir -p "$BUILD_DIR/static"
        cp -r build/* "$BUILD_DIR/static/"
    else
        print_warning "No package.json found, creating basic frontend structure"
        mkdir -p "$BUILD_DIR/static"
        cat > "$BUILD_DIR/static/index.html" << 'EOF'
<!DOCTYPE html>
<html>
<head>
    <title>ArXiv Subscription Platform</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        .container { max-width: 800px; margin: 0 auto; }
        .header { background: #2563eb; color: white; padding: 20px; border-radius: 8px; }
        .content { padding: 20px; background: #f8fafc; border-radius: 8px; margin-top: 20px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>ArXiv Subscription Platform</h1>
            <p>Intelligent paper discovery powered by AI</p>
        </div>
        <div class="content">
            <h2>Welcome</h2>
            <p>The platform is running! API endpoints are available at <a href="/api/docs">/api/docs</a></p>
            <p>Frontend is being served statically. Full React frontend available in development mode.</p>
        </div>
    </div>
</body>
</html>
EOF
    fi
    
    cd "$PROJECT_ROOT"
    print_success "Frontend build completed"
}

build_backend() {
    print_status "Building backend services..."
    
    # Activate virtual environment
    source "$VENV_DIR/bin/activate"
    
    # Create build directory
    mkdir -p "$BUILD_DIR/backend"
    
    # Copy backend code
    cp -r "$BACKEND_DIR"/* "$BUILD_DIR/backend/"
    
    # Create configuration files
    cat > "$BUILD_DIR/backend/.env" << EOF
ENVIRONMENT=$ENVIRONMENT
DATABASE_URL=$DATABASE_URL
REDIS_URL=$REDIS_URL
SECRET_KEY=$(python3 -c 'import secrets; print(secrets.token_urlsafe(32))')
ALLOWED_HOSTS=localhost,127.0.0.1,0.0.0.0
PORT=$PORT
EOF
    
    print_success "Backend build completed"
}

create_service_files() {
    print_status "Creating service files..."
    
    mkdir -p "$BUILD_DIR/services"
    
    # Main API service
    cat > "$BUILD_DIR/services/arxiv-api.service" << EOF
[Unit]
Description=ArXiv Subscription Platform API
After=network.target postgresql.service redis.service

[Service]
Type=exec
User=$USER
WorkingDirectory=$BUILD_DIR/backend
Environment=PATH=$VENV_DIR/bin
ExecStart=$VENV_DIR/bin/gunicorn -w 4 -b 0.0.0.0:$PORT main:app
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
EOF

    # ArXiv Scraper service
    cat > "$BUILD_DIR/services/arxiv-scraper.service" << EOF
[Unit]
Description=ArXiv Paper Scraper
After=network.target postgresql.service

[Service]
Type=exec
User=$USER
WorkingDirectory=$BUILD_DIR/backend/arxiv_scraper_service
Environment=PATH=$VENV_DIR/bin
ExecStart=$VENV_DIR/bin/python main.py
Restart=always
RestartSec=30

[Install]
WantedBy=multi-user.target
EOF

    # Email service
    cat > "$BUILD_DIR/services/arxiv-email.service" << EOF
[Unit]
Description=ArXiv Email Service
After=network.target postgresql.service redis.service

[Service]
Type=exec
User=$USER
WorkingDirectory=$BUILD_DIR/backend/email_service
Environment=PATH=$VENV_DIR/bin
ExecStart=$VENV_DIR/bin/python main.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

    # Nginx configuration for static files
    cat > "$BUILD_DIR/services/nginx-arxiv.conf" << EOF
server {
    listen 80;
    server_name localhost;
    
    # Frontend static files
    location / {
        root $BUILD_DIR/static;
        try_files \$uri \$uri/ /index.html;
    }
    
    # API proxy
    location /api/ {
        proxy_pass http://127.0.0.1:$PORT/;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }
    
    # Health check
    location /health {
        proxy_pass http://127.0.0.1:$PORT/health;
    }
}
EOF

    print_success "Service files created"
}

create_startup_script() {
    print_status "Creating startup script..."
    
    cat > "$BUILD_DIR/start.sh" << 'EOF'
#!/bin/bash

# ArXiv Subscription Platform Startup Script

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VENV_DIR="$PROJECT_ROOT/../venv"
LOG_DIR="$PROJECT_ROOT/../logs"

# Create log directory
mkdir -p "$LOG_DIR"

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m'

print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

# Activate virtual environment
source "$VENV_DIR/bin/activate"

# Start services
print_status "Starting ArXiv Subscription Platform..."

# Start Redis if not running
if ! pgrep redis-server > /dev/null; then
    print_status "Starting Redis..."
    redis-server --daemonize yes
fi

# Start main API
print_status "Starting API service..."
cd "$PROJECT_ROOT/backend"
gunicorn -w 4 -b 0.0.0.0:8000 main:app --daemon \
    --pid "$LOG_DIR/api.pid" \
    --log-file "$LOG_DIR/api.log" \
    --access-logfile "$LOG_DIR/api_access.log"

# Start scraper service
print_status "Starting scraper service..."
cd "$PROJECT_ROOT/backend/arxiv_scraper_service"
python main.py > "$LOG_DIR/scraper.log" 2>&1 &
echo $! > "$LOG_DIR/scraper.pid"

# Start email service
print_status "Starting email service..."
cd "$PROJECT_ROOT/backend/email_service"
python main.py > "$LOG_DIR/email.log" 2>&1 &
echo $! > "$LOG_DIR/email.pid"

print_success "All services started!"
print_status "API running on http://localhost:8000"
print_status "API documentation at http://localhost:8000/docs"
print_status "Logs available in $LOG_DIR"

# Wait and show status
sleep 3
ps aux | grep -E "(gunicorn|python.*main.py)" | grep -v grep
EOF

    chmod +x "$BUILD_DIR/start.sh"
    
    # Create stop script
    cat > "$BUILD_DIR/stop.sh" << 'EOF'
#!/bin/bash

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_DIR="$PROJECT_ROOT/../logs"

echo "Stopping ArXiv Subscription Platform..."

# Stop services using PID files
for service in api scraper email; do
    if [ -f "$LOG_DIR/${service}.pid" ]; then
        echo "Stopping $service..."
        kill $(cat "$LOG_DIR/${service}.pid") 2>/dev/null || true
        rm -f "$LOG_DIR/${service}.pid"
    fi
done

# Kill any remaining processes
pkill -f "gunicorn.*main:app" || true
pkill -f "python.*main.py" || true

echo "All services stopped"
EOF

    chmod +x "$BUILD_DIR/stop.sh"
    
    print_success "Startup scripts created"
}

create_readme() {
    print_status "Creating deployment README..."
    
    cat > "$BUILD_DIR/README.md" << 'EOF'
# ArXiv Subscription Platform - Native Deployment

This is a native (non-Docker) deployment of the ArXiv Subscription Platform.

## Quick Start

1. **Start the platform:**
   ```bash
   ./start.sh
   ```

2. **Access the platform:**
   - Web interface: http://localhost:80 (if Nginx configured)
   - API: http://localhost:8000
   - API Documentation: http://localhost:8000/docs

3. **Stop the platform:**
   ```bash
   ./stop.sh
   ```

## Services

- **API Service**: Main FastAPI backend (port 8000)
- **Scraper Service**: Daily ArXiv paper harvesting
- **Email Service**: Personalized email delivery
- **Redis**: Caching and session storage
- **PostgreSQL**: Main database

## Logs

All service logs are stored in `../logs/`:
- `api.log` - Main API logs
- `scraper.log` - Paper scraping logs  
- `email.log` - Email service logs

## Configuration

Environment variables are set in `backend/.env`:
- `DATABASE_URL` - PostgreSQL connection string
- `REDIS_URL` - Redis connection string
- `SECRET_KEY` - Application secret key
- `PORT` - API service port

## Health Checks

Check service status:
```bash
curl http://localhost:8000/health
```

## Troubleshooting

1. **Database connection issues:**
   - Check PostgreSQL is running: `systemctl status postgresql`
   - Verify connection: `psql postgresql://arxiv_user:arxiv_pass@localhost:5432/arxiv_platform`

2. **Redis connection issues:**
   - Check Redis is running: `redis-cli ping`
   - Start Redis: `redis-server --daemonize yes`

3. **Port conflicts:**
   - Change PORT in build script and rebuild
   - Check port usage: `netstat -tulpn | grep :8000`

## Production Setup

For production deployment:

1. **Install as system services:**
   ```bash
   sudo cp services/*.service /etc/systemd/system/
   sudo systemctl daemon-reload
   sudo systemctl enable arxiv-api arxiv-scraper arxiv-email
   sudo systemctl start arxiv-api arxiv-scraper arxiv-email
   ```

2. **Setup Nginx:**
   ```bash
   sudo cp services/nginx-arxiv.conf /etc/nginx/sites-available/arxiv
   sudo ln -s /etc/nginx/sites-available/arxiv /etc/nginx/sites-enabled/
   sudo systemctl reload nginx
   ```

3. **Setup SSL with Let's Encrypt:**
   ```bash
   sudo certbot --nginx -d your-domain.com
   ```

## Monitoring

Monitor services:
```bash
sudo systemctl status arxiv-api
sudo journalctl -u arxiv-api -f
```

## Backup

Database backup:
```bash
pg_dump arxiv_platform > backup_$(date +%Y%m%d).sql
```
EOF

    print_success "README created"
}

main() {
    print_status "Building ArXiv Subscription Platform (Native Deployment)"
    print_status "Project root: $PROJECT_ROOT"
    print_status "Environment: $ENVIRONMENT"
    
    # Create necessary directories
    mkdir -p "$BUILD_DIR" "$LOG_DIR"
    
    # Run build steps
    check_dependencies
    setup_python_environment
    setup_database
    build_frontend
    build_backend
    create_service_files
    create_startup_script
    create_readme
    
    print_success "Build completed successfully!"
    print_status "To start the platform: cd $BUILD_DIR && ./start.sh"
    print_status "Access the API at: http://localhost:$PORT"
    print_status "API documentation at: http://localhost:$PORT/docs"
}

# Handle command line arguments
case "${1:-}" in
    "clean")
        print_status "Cleaning build directory..."
        rm -rf "$BUILD_DIR"
        print_success "Clean completed"
        ;;
    "rebuild")
        print_status "Rebuilding platform..."
        rm -rf "$BUILD_DIR"
        main
        ;;
    "deps")
        check_dependencies
        ;;
    *)
        main
        ;;
esac